import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/Login/index.vue') },
    {
      path: '/',
      component: () => import('@/views/Layout/index.vue'),
      redirect: '/home',
      children: [
        { path: '/home', component: () => import('@/views/Home/index.vue') ,meta:{title:'首页'}},
        { path: '/article', component: () => import('@/views/Article/index.vue'),meta:{title:'健康招聘'} },
        { path: '/notify', component: () => import('@/views/Notify/index.vue'),meta:{title:'消息中心'} },
        { path: '/user', component: () => import('@/views/User/index.vue') ,meta:{title:'我的'}}
      ]
    },
    {
      path: '/user/patient',
      component: () => import('@/views/User/PatientPage.vue'),
      meta: { title: '家庭档案' }
    }
  ]
})

// 设置白名单
const whiteList = ['/login', 'register']
// 访问权限控制
router.beforeEach( to => {
  const store = useUserStore()
  if (!store.user?.token && !whiteList.includes(to.path)) {
    // return 跳转到登录页
    return '/login'
  }
})

router.afterEach( to => {
  document.title = `优医问诊-${to.meta.title || ''}`
})

export default router
